<style lang="less">
  @import './base-info.less';
</style>

<template>
  <div class="base-info">
    <div class="title-option-box">
      <h1 class="title">基本信息</h1>
      <p class="option">
        <Button type="primary" @click="saveBaseInfo">保存</Button>
        <Button type="primary" disabled>
          <Icon type="ios-arrow-back" size="15"></Icon>
        </Button>
        <Button @click="nextBtn" type="primary" :disabled="nextDisabled">
          <Icon type="ios-arrow-forward" size="15"></Icon>
        </Button>
      </p>
    </div>
    <div class="base-info-content">
      <Form
        class="base-info-form"
        ref="baseInfoForm"
        :model="baseInfoForm"
        :rules="baseInfoFormRules"
        label-position="left"
        :label-width="100">
        <!-- 项目信息 -->
        <h2 class="base-info-subtitle">项目信息</h2>
        <FormItem v-if="optionType !== 'create'" label="项目ID" prop="projectId">
          <Input v-model="baseInfoForm.projectId" disabled></Input>
        </FormItem>
        <FormItem label="项目名称" prop="projectName">
          <Input v-model="baseInfoForm.projectName" placeholder="请输入项目名称"></Input>
        </FormItem>
        <FormItem label="项目描述" prop="projectDesc">
          <Input type="textarea" :rows="4" v-model="baseInfoForm.projectDesc" placeholder="请输入项目描述"></Input>
        </FormItem>
        <FormItem label="业务分类" prop="bizType">
          <Cascader
            :data="bizTypeDic"
            v-model="baseInfoForm.bizType"
            change-on-select></Cascader>
          <!-- <Select v-model="baseInfoForm.bizType">
            <Option value="test-1">场景-1</Option>
          </Select> -->
        </FormItem>
        <FormItem label="更改者" prop="updateBy">
          <Input v-model="baseInfoForm.updateBy" disabled></Input>
        </FormItem>
        <FormItem label="更改时间" prop="updateAt">
          <Input v-model="baseInfoForm.updateAt" disabled></Input>
        </FormItem>
        <FormItem label="创建者" prop="createBy">
          <Input v-model="baseInfoForm.createBy" disabled></Input>
        </FormItem>
        <FormItem label="创建时间" prop="createAt">
          <Input v-model="baseInfoForm.createAt" disabled></Input>
        </FormItem>
        <!-- 权限共享 -->
        <h2 class="base-info-subtitle">权限共享</h2>
        <FormItem class="inline-item" label="选择部门">
          <Cascader
            :data="departmentList"
            v-model="selectedDepartment"
            change-on-select
            @on-change="changeDepartment"></Cascader>
        </FormItem>
        <FormItem class="inline-item min-label" label="选择角色">
          <Select v-model="selectedRole" clearable @on-change="changeRole" @on-clear="clearRole">
            <Option v-for="item in roleList" :key="item.roleCode" :value="item.roleCode">{{ item.roleName }}</Option>
          </Select>
        </FormItem>
        <FormItem class="inline-item min-label" label="选择用户">
          <Select v-model="selectedUser" placeholder="请先选择部门、角色">
            <Option v-for="item in userList" :key="item.userCode" :value="item.userCode">{{ item.userName }}</Option>
          </Select>
          <Button type="primary" style="position: absolute; left: 234px;" @click="addShareUser" :disabled="!selectedUser.length">添加</Button>
        </FormItem>
        <FormItem class="share-box" label="可编辑权限">
          <Tag v-for="item in selectedUserList" :key="item.userCode" closable @on-close="handleCloseTag">
            {{ item.userName }}
          </Tag>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
import { showMessageTip, addProp, getAllParentCodes } from '@/libs/util'
import { queryDictByKeyApi } from '@/api/business-type'
import { createProject, getProjectBaseInfoById, updateProjectBaseInfoById, updateSharingById, getSharingById, queryDepartmentList, queryRoleList, queryUserList } from '@/api/my-project'
export default {
  name: 'base_info',
  data () {
    return {
      nextBtnDisable: true,
      // 业务分类字典
      bizTypeDic: [],

      baseInfoForm: {
        projectId: '',
        projectName: '',
        projectDesc: '',
        bizType: [],
        updateBy: '',
        updateAt: '',
        createBy: '',
        createAt: '',
        department: '',
        role: '',
        user: '',
        juris: ''
      },
      baseInfoFormRules: {
        projectName: [{
          required: true,
          message: '项目名称不能为空',
          trigger: 'blur'
        }],
        projectDesc: [{
          required: true,
          message: '项目描述不能为空',
          trigger: 'blur'
        }],
        bizType: [{
          required: 'true',
          type: 'array',
          message: '业务场景不能为空'
        }]
      },
      // 共享-可编辑用户列表
      selectedUserList: [],
      departmentList: [],
      selectedDepartment: [],

      roleList: [],
      selectedRole: '',

      userList: [],
      selectedUser: ''
    }
  },
  computed: {
    // 判断当前路由下是'新建' or '编辑'
    optionType () {
      return this.$route.params.projectId === '_create' ? 'create' : 'edit'
    },
    nextDisabled () {
      return this.optionType === 'edit' ? false : this.nextBtnDisable
    }
  },
  methods: {
    setDicList () {
      const params = {
        dictKey: 'businessType'
      }
      queryDictByKeyApi(params).then((res) => {
        if (res.data.code === 2000 && res.data.data && res.data.data.children) {
          if (this.optionType === 'edit') this.getProjectBaseInfo()
          const propArray = [{
            targetKey: 'dictId',
            hopeKey: 'value'
          }, {
            targetKey: 'dictName',
            hopeKey: 'label'
          }]
          this.bizTypeDic = addProp(res.data.data.children, [], propArray)
          console.log('----bizTypeDic', this.bizTypeDic)
        }
      })
    },
    nextBtn () {
      const params = {
        activeName: 'baseInfo',
        option: 'next'
      }
      this.$emit('on-move-forward', params)
    },
    // 编辑模式下 获取表单信息
    getProjectBaseInfo () {
      const params = {
        projectId: this.$route.params.projectId
      }
      getProjectBaseInfoById(params).then((res) => {
        if (res.data.code === 2000) {
          const result = res.data.data
          const checkNode = result.bizType
          result.bizType = getAllParentCodes(this.bizTypeDic, checkNode)
          this.baseInfoForm = result
        } else {
          this.$Message.error(res.data.msg || '加载失败，请重试')
        }
      })
    },
    saveBaseInfo () {
      this.$refs.baseInfoForm.validate((valid) => {
        if (!valid) return
        if (this.optionType === 'create') {
          const bizType = this.baseInfoForm.bizType[this.baseInfoForm.bizType.length - 1] || ''
          const { projectName, projectDesc } = this.baseInfoForm
          createProject({ projectName, projectDesc, bizType }).then((res) => {
            const code = res.data.code
            const successText = '新建成功'
            const errorText = res.data.msg || '新建失败，请重试'
            showMessageTip(this, code, successText, errorText)
            if (code === 2000) {
              this.nextBtnDisable = false
              this.$emit('on-save-projectid', res.data.data.projectId)
              if (this.selectedUserList.length > 0) this.updateSharing(res.data.data.projectId)
            }
          })
        } else {
          const params = {
            projectId: this.$route.params.projectId
          }
          const data = JSON.parse(JSON.stringify(this.baseInfoForm))
          data.bizType = data.bizType[data.bizType.length - 1] || ''
          updateProjectBaseInfoById(params, data).then((res) => {
            const code = res.data.code
            const successText = '更新成功'
            const errorText = res.data.msg || '新建失败，请重试'
            showMessageTip(this, code, successText, errorText)
          })
          this.updateSharing(this.$route.params.projectId)
        }
      })
    },
    // 关闭标签事件
    handleCloseTag (value) {
      const index = this.selectedUserList.findIndex(item => value === item)
      this.selectedUserList.splice(index, 1)
    },
    // 添加角色按钮
    addShareUser () {
      if (this.selectedUserList.findIndex(item => item.userCode === this.selectedUser) > -1) {
        this.$Message.warning({
          content: '所选角色已存在',
          duration: 4
        })
      } else {
        const item = this.userList.filter(v => v.userCode === this.selectedUser)[0]
        this.selectedUserList.push(item)
      }
    },
    // 更新共享权限
    updateSharing (projectId) {
      const params = {
        projectId
      }
      const data = this.selectedUserList.map(item => item.userCode)
      updateSharingById(params, data).then((res) => {
        console.log('--res', res)
      })
    },
    // 获取当前“可编辑权限”用户列表
    getShareList () {
      const params = {
        projectId: this.$route.params.projectId
      }
      getSharingById(params).then((res) => {
        this.selectedUserList = res.data.data && res.data.data.length ? res.data.data : []
      })
    },
    // 获取部门列表
    getDepartmentList () {
      queryDepartmentList().then((res) => {
        this.departmentList = res.data.data
      })
    },
    // 获取角色列表
    getRoleList () {
      queryRoleList().then((res) => {
        this.roleList = res.data.data
      })
    },
    /**
     * 获取用户列表
     * @param [lstDeptCode] {Array} 选中部门列表
     * @param [lstRoleCode] {Array} 选中角色列表
      */
    getUserList (lstDeptCode, lstRoleCode) {
      this.selectedUser = ''
      const params = {
        lstDeptCode,
        lstRoleCode
      }
      queryUserList(params).then((res) => {
        this.userList = res.data.data
      })
    },
    // 改变department列表选中事件
    changeDepartment (value) {
      const lstDeptCode = value.length ? [value[ value.length - 1 ]] : []
      const lstRoleCode = this.selectedRole ? [this.selectedRole] : []
      this.getUserList(lstDeptCode, lstRoleCode)
    },
    // 改变角色列表选中事件
    changeRole (value) {
      const lstDeptCode = this.selectedDepartment.length ? [this.selectedDepartment[this.selectedDepartment.length - 1]] : []
      const lstRoleCode = value.length ? [value] : []
      this.getUserList(lstDeptCode, lstRoleCode)
    },
    // 清空角色列表事件
    clearRole () {
      const lstDeptCode = this.selectedDepartment.length ? [this.selectedDepartment[this.selectedDepartment.length - 1]] : []
      const lstRoleCode = []
      this.getUserList(lstDeptCode, lstRoleCode)
    }
  },
  mounted () {
    this.setDicList()
    if (this.optionType === 'edit') {
      this.getShareList()
    }
    // 获取部门、角色下拉列表
    this.getDepartmentList()
    this.getRoleList()
    this.getUserList([], [])
  }
}
</script>

<style>

</style>
